package io.kiki.sba.registry.server.clientInterface.bootstrap;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;

import java.util.concurrent.atomic.AtomicBoolean;


public class SessionServerInitializer implements SmartLifecycle {

    private static final Logger logger = LoggerFactory.getLogger(SessionServerInitializer.class);

    @Autowired
    private Bootstrap bootstrap;

    private AtomicBoolean running = new AtomicBoolean(false);

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void start() {
        try {
            bootstrap.start();
            logger.info("Started SessionServer");

            SessionServerInitializer.this.running.set(true);
        } catch (Throwable ex) {
            SessionServerInitializer.this.running.set(false);
            logger.error("Could not initialize Session server!", ex);
            Runtime.getRuntime().halt(-1);
        }
    }

    @Override
    public void stop() {
        this.running.set(false);
        bootstrap.destroy();
    }

    @Override
    public boolean isRunning() {
        return this.running.get();
    }

    @Override
    public int getPhase() {
        return 0;
    }

    @Override
    public void stop(Runnable callback) {
        callback.run();
        this.running.set(false);
    }
}
